package arrAndstr;

/*
    230. 二叉搜索树中第 K 小的元素
    为了防止static被其他线程影响，可以使用成员变量：
        class Solution{
            private int xxx = 0;
            private int count = 0;
        }
        只要没有static方法即可
 */
public class T230 {

  public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

    private static int result = 0;  // 存储最终结果
    private static int nowSmall = 0;   // 记录当前遍历到第几个节点
    public static int kthSmallest(TreeNode root, int k) {
        getKthSmalllest(root, k);
        return result;
    }

    private static void getKthSmalllest(TreeNode root, int k) {
        if (root == null)   return;

        getKthSmalllest(root.left, k);

        nowSmall++;
        if (nowSmall == k)  {
            result = root.val;
            return;
        }

        getKthSmalllest(root.right, k);
    }

    public static void main(String[] args) {
        TreeNode node = new TreeNode(3);
        node.left = new TreeNode(1);
        node.left.right = new TreeNode(2);
        node.right = new TreeNode(4);

        System.out.println(kthSmallest(node, 1));
    }

}
